<template>
    <div ref="container">
        <div style="padding-left: 35px; padding-top:20px;">
            <el-button @click='zoomOut' ref="zoomOut">缩小</el-button>
            <el-button @click='zoomIn' ref="zoomIn">放大</el-button>
            <el-button @click="expandAll">全部展开</el-button>
            <el-button @click="unExpandAll">全部收起</el-button>
            <!--<el-button @click="downloadImg">下载图片</el-button>-->        <!--<el-upload :auto-upload="false" :show-file-list="false" :on-change="handleUpload" style="display: inline-block">-->
            <!--<el-button type="warning"  icon="el-icon-upload"-->
            <!--style="margin-left: 10px; display: flex" >-->
            <!--导入Bom-->
            <!--</el-button>-->
            <!--</el-upload>
    -->
        </div>
        <!--<el-button @click="selectNode">指定选中</el-button>-->
        <div id="jsmind_container" style="width: 100%;height: 80vh;overflow-y: scroll;" ref="jsmindContainer"></div>
        <select-work-list ref="selectWorkList" @success="addWorkList"></select-work-list>
        <bom-list-form ref="bomListForm" @success="addMaterial"></bom-list-form>
        <bom-list-copy ref="bomListCopy" @success="this.refreshJsMind"></bom-list-copy>
        <bom-list-edit ref="bomListEdit" @success="this.refreshJsMind"></bom-list-edit>
        <bom-list-data ref="bomListData"></bom-list-data>
    </div>

</template>

<script>
    import { mapGetters } from "vuex";
    import '@/styles/jsmind.css'

    import { jsmindInit } from '@/utils/jsmind.js'
    // jsmindInit(window)

    import { init } from '@/utils/jsmind.menu.js'
    // init(window)
    import {checkBom, getBomTree,addWorkList, addMaterial,remove,checkBomChild,importBomList, checkBomParent } from "@/api/anwise/material/bom_list";
    import {getMaterialByNo } from "@/api/anwise/material/material";
    import selectWorkList from "@/views/anwise/material/components/select_work_list.vue";
    import bomListForm from "@/views/anwise/material/components/bom_list_form.vue";
    import bomListEdit from "@/views/anwise/material/components/bom_list_edit.vue";
    import bomListData from "@/views/anwise/material/components/bom_list_data.vue";
    import bomListCopy from "@/views/anwise/material/components/bom_list_copy.vue";

    export default {
        components: {
            selectWorkList,
            bomListForm,
            bomListEdit,
            bomListData,
            bomListCopy
        },
        data() {
            return {
                selectedNode: '',
                selectedMaterialNo: '',
                isAssign:'',
                form: {},
                query: {},
                loading: true,
                dateFormat: 'YYYY-MM-DD',
                pickerOptions: {},
                page: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                search: {},
                selectionList: [],
                option: {
                    height: '100%',
                    calcHeight: 30,
                    tip: false,
                    searchShow: true,
                    searchMenuSpan: 6,
                    border: true,
                    index: true,
                    labelWidth: 150,
                    indexWidth: 100,
                    menu: false,
                    menuWidth: 120,
                    addBtn: false,
                    editBtn: false,
                    viewBtn: false,
                    delBtn: false,
                    searchEnter: true,
                    stripe: true,
                    searchIndex: 3,
                    searchIcon: false,
                    highlightCurrentRow: true,
                    column: [

                        {
                            label: "编号代码",
                            prop: "codeNo",
                            type: "input",
                            search: true,
                            overHidden: true,
                            sortable: true,
                            rules: [{
                                required: true,
                                message: "请输入编号代码",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "编号名称",
                            prop: "codeName",
                            type: "input",
                            search: true,
                            overHidden: true,
                            sortable: true,
                            rules: [{
                                required: true,
                                message: "请输入编号名称",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "备注",
                            prop: "remark",
                            type: "textarea",
                            overHidden: true,
                            sortable: true,
                            span: 24,
                        },
                        {
                            label: "创建人",
                            prop: "createUserName",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                        },
                        {
                            label: "创建时间",
                            prop: "createTime",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            search: false,
                        },
                    ]
                },
                data: [],
                dialogVisible: false,
                mind: {
                    meta: {/* 元数据，定义思维导图的名称、作者、版本等信息 */
                        name: 'ztengluo',
                        author: 'hizzgdev@163.com',
                        version: '0.2'
                    },
                    format: 'node_tree',
                    // format: 'node_array',
                    data:{},
                },
                jmOptions: {
                    container: 'jsmind_container', // [必选] 容器的ID
                    editable: true, // [可选] 是否启用编辑
                    // theme: 'clouds', // [可选] 主题
                    theme: 'primary', // [可选] 主题
                    support_html: true,    // 是否支持节点里的HTML元素
                    view: {
                        engine: 'canvas',   // 思维导图各节点之间线条的绘制引擎
                        hmargin: 200,        // 思维导图距容器外框的最小水平距离
                        vmargin: 50,         // 思维导图距容器外框的最小垂直距离
                        line_width: 1,       // 思维导图线条的粗细
                        line_color: '#C18AFB'   // 思维导图线条的颜色
                    },
                    menuOpts: {
                        showMenu: true,
                        switchMidStage: true, //开启中台
                        newNodeText: '新的节点',
                        injectionList: [

                            {
                                target: 'addChild', text: '编辑',
                                callback: (node, fn) => {
                                    this.selectedNode = this.jm.get_selected_node();
                                    console.log(this.selectedNode);
                                    if(this.selectedNode.isroot) {
                                        this.$message({
                                            type: "error",
                                            message: "无法编辑根节点！"
                                        });
                                        return;
                                    }
                                    console.log(this.selectedNode.data);
                                    checkBomParent(this.selectedNode.data.nodeNo, this.selectedNode.data.parentNo).then(res =>{
                                        if(!res.data.success) {
                                            this.$message({
                                                type: "error",
                                                message: res.data.msg || "Bom清单已审核！"
                                            });
                                            return;
                                        } else {
                                            this.$refs.bomListEdit.show("修改【"+this.selectedNode.data.nodeNo+"】",node.id.substring(node.id.lastIndexOf(",") + 1),this.selectedNode.data.parentNo);
                                        }
                                    });
                                    // if (this.selectedNode.data.type ===4) {
                                    //     this.$message({
                                    //         type: "error",
                                    //         message: "无法编辑工序！"
                                    //     });
                                    //     return;
                                    // }

                                    // this.dialogVisible = true
                                    // this.options.menuOpts.newNodeText = 'aaaaaaaaaaaaa'
                                    // fn('powerful133333333');
                                    console.log(node)
                                }
                            },
                            {
                                target: 'addChild', text: 'Bom数据展示',
                                callback: (node, fn) => {
                                    this.selectedNode = this.jm.get_selected_node();
                                    console.log(this.selectedNode)
                                    this.$refs.bomListData.show("【"+this.selectedNode.data.nodeNo+"】Bom数据展示",this.selectedNode.data);

                                }
                            },
                            {
                                target: 'addChild', text: '添加工序',
                                callback: (node, fn) => {

                                    this.selectedNode = this.jm.get_selected_node();
                                    console.log(this.selectedNode);
                                    if (this.selectedNode.data.type =='原料' || this.selectedNode.data.type =='工序') {
                                        this.$message({
                                            type: "error",
                                            message: "原料/工序无法再添加子项！"
                                        });
                                        return;
                                    }

                                    checkBomParent(this.selectedNode.data.nodeNo, this.selectedNode.data.parentNo).then(res =>{
                                        if(!res.data.success) {
                                            this.$message({
                                                type: "error",
                                                message: res.data.msg || "Bom清单已审核！"
                                            });
                                            return;
                                        } else {
                                            this.$refs.selectWorkList.showSelect();
                                        }
                                    });


                                    // this.dialogVisible = true
                                    // this.options.menuOpts.newNodeText = 'aaaaaaaaaaaaa'
                                    // fn('powerful133333333');
                                    console.log(node)
                                }
                            },
                            {
                                target: 'addChild', text: '添加物料',
                                callback: (node, fn) => {
                                    this.selectedNode = this.jm.get_selected_node();
                                    console.log(this.selectedNode)
                                    if (this.selectedNode.data.type =='原料' || this.selectedNode.data.type =='工序') {
                                        this.$message({
                                            type: "error",
                                            message: "原料/工序无法再添加子项！"
                                        });
                                        return;
                                    }
                                    checkBomParent(this.selectedNode.data.nodeNo, this.selectedNode.data.parentNo).then(res =>{
                                        if(!res.data.success) {
                                            this.$message({
                                                type: "error",
                                                message: res.data.msg || "Bom清单已审核！"
                                            });
                                            return;
                                        } else {
                                            this.$refs.bomListForm.show("为【"+this.selectedNode.data.nodeNo+"】添加物料",this.selectedNode.data.nodeNo);
                                        }
                                    });

                                }
                            },
                            {
                                target: 'delete', text: '删除节点',
                                callback: (node, next) =>{
                                    this.selectedNode = this.jm.get_selected_node();
                                    console.log(this.selectedNode);
                                    checkBomParent(this.selectedNode.data.nodeNo, this.selectedNode.data.parentNo).then(res =>{
                                        if(!res.data.success) {
                                            this.$message({
                                                type: "error",
                                                message: res.data.msg || "Bom清单已审核！"
                                            });
                                            return;
                                        } else {
                                            this.$confirm("确定将选择节点以及子节点删除?", {
                                                confirmButtonText: "确定",
                                                cancelButtonText: "取消",
                                                type: "warning"
                                            })
                                                .then(() => {
                                                    console.log(this.selectedNode);
                                                    remove(this.selectedNode.id.substring(this.selectedNode.id.lastIndexOf(",") + 1)).then(res => {
                                                        if (res.data.success) {
                                                            // this.jm.get_selected_node()._data.view.element.remove()
                                                            if (this.selectedNode.isroot) {
                                                                document.querySelector('.theme-primary').style = 'display:none'
                                                                document.querySelector('.jsmind').style = 'display:none'
                                                            } else{
                                                                next(node.id)
                                                            }
                                                            this.$emit("success");

                                                            this.$message({
                                                                type: "success",
                                                                message: "操作成功!"
                                                            });
                                                        } else {
                                                            this.$message({
                                                                type: "error",
                                                                message: res.data.msg || "删除失败!"
                                                            });
                                                            return;
                                                        }
                                                    })
                                                })
                                        }
                                    });
                                    // if (this.selectedNode.isroot) {
                                    //
                                    //     // document.querySelector('.theme-primary').style = 'display:none'
                                    //     this.$message({
                                    //         type: "error",
                                    //         message: "不允许删除根节点!"
                                    //     });
                                    //     return;
                                    // }

                                }
                            },

                        ],
                    },
                },
                jm: '',


            };
        },
        mounted() {
            init(window)
            this.drawMind()
        },
        methods: {
            showAdd(node) {
                this.selectedNode = node;
                this.$refs.modal_1.show();
            },
            opened() {
                this.onLoadWorkList(this.page);
            },
            close() {

            },
            dblclick(row) {
                console.log(this.selectedNode);
                console.log('@@@@@@@@@@@@@@', row.codeNo, row.codeName, row.id, row);
                let newNode = {
                    parentId: this.selectedNode.id.substring(this.selectedNode.id.lastIndexOf(",") + 1),
                    codeNo: row.codeNo,
                    codeName: row.codeName,
                }
                this.$refs.modal_1.hide();
                addReturn(newNode).then((res) => {
                    if (res.data.success) {
                        this.$message({
                            type: "success",
                            message: "添加成功!"
                        });
                        this.jm.select_clear();
                        this.refreshJsMind();

                        // const topic = `<span style="font-size:14px;">[${row.codeNo}]</span><br>${row.codeName}`
                        // const nodeid = new Date().getTime()
                        // this.jm.add_node(this.selectedNode, nodeid, topic)
                        // this.jm.select_node(nodeid);
                        // this.onLoad();
                        this.$emit("success");
                    } else {
                        this.$message({
                            type: "error",
                            message: "添加失败!"
                        });
                    }
                }, error => {
                    window.console.log(error);
                });

            },
            refreshJsMind() {
                getBomTree(this.selectedMaterialNo).then(res => {
                    if (res.data.success) {
                        console.log(res.data)
                        this.mind.data = res.data.data[0];
                        this.mind.data.isroot = true;
                        this.jm.show( this.mind);
                    }
                });
            },
            addWorkList(data) {
                console.log(data);
                let work = {
                    parentNo:this.selectedNode.id.substring(this.selectedNode.id.lastIndexOf(",") + 1),
                    nodeNo: data.id
                }
                addWorkList(work).then(res =>{
                    if (res.data.success) {
                        this.$message({
                            type: "success",
                            message: "添加成功!"
                        });
                        this.jm.select_clear();
                        this.refreshJsMind();
                    }
                })
            },

            addMaterial(data) {
                console.log(data);
                data.parentNo = this.selectedNode.data.nodeNo;
                addMaterial(data).then(res =>{
                    if (res.data.success) {
                        this.$message({
                            type: "success",
                            message: "添加成功!"
                        });
                        this.jm.select_clear();
                        this.refreshJsMind();
                    }
                })

            },

            handleDbClick(row) {
                this.selectedMaterialNo = row.materialNo;
                this.isAssign = row.isAssign;
                checkBom(row.materialNo).then(rs => {
                    if (rs.data.success) {
                        getBomTree(this.selectedMaterialNo).then(res => {
                            if (res.data.success) {
                                console.log(res.data)
                                this.mind.data = res.data.data[0];
                                this.mind.data.isroot = true;
                                console.log("this.mind", this.mind);
                                if(document.querySelector('.theme-primary')){
                                    document.querySelector('.theme-primary').style = 'display:block'
                                    document.querySelector('.jsmind').style = 'display:block'
                                }
                                this.jm.show( this.mind);
                                const left = document.querySelector('.theme-primary').getBoundingClientRect().left
                                document.querySelector('.theme-primary').style.transform = 'translateX(-'+left+'px) scale(0.8)';
                                document.querySelector('.jsmind').style.transform = 'translateX(-'+left+'px)  scale(0.8)';
                            }
                        });
                    }
                });
            },
            //获取所有父级id
            findParentIds(dataSource, nodeId) {
                const parentIds = [];
                function traverse(node, nodeId) {
                    if (node.id === nodeId) return true;
                    if (node.children) {
                        for (const childNode of node.children) {
                            if (traverse(childNode, nodeId)) {
                                parentIds.push(node.id);
                                return true;
                            }
                        }
                    }
                    return false;
                }
                for (const node of dataSource) {
                    if (traverse(node, nodeId)) break;
                }
                return parentIds; // 返回所有父节点ID的数组
            },
            selectNode() {

                this.jm.expand_node(2)
                this.jm.expand_node(88)

                this.jm.select_node(91);
                // this.jm.toggle_node('open2')
            },
            drawMind() {
                jsmindInit(window)
                jsMind.preventMindEventDefault();
                this.jm = new jsMind(this.jmOptions);
                // this.jm.show(this.mind);
                // this.zoomOut();
                // this.zoomOut();
                // this.jm.enable_edit()
                // this.jm.enable_event_handle('dblclick')
            },
            // 缩小
            zoomOut() {
                if(document.querySelector('.theme-primary')){
                    let zoom = document.querySelector('.theme-primary').style.transform ? document.querySelector('.theme-primary').style.transform.split('scale')[1].substring(1).split(')')[0] : 0
                    let num = zoom - 0.1
                    if(num <=0 )  num = 0
                    document.querySelector('.theme-primary').style.transform = 'scale('+num+')';
                    document.querySelector('.jsmind').style.transform = 'scale('+num+')';
                }
            },
            // 放大
            zoomIn() {
                if(document.querySelector('.theme-primary')){
                    let zoom = document.querySelector('.theme-primary').style.transform ? document.querySelector('.theme-primary').style.transform.split('scale')[1].substring(1).split(')')[0] : 0
                    let num = parseFloat(zoom) + 0.1
                    if(num >=1)  num = 1
                    document.querySelector('.theme-primary').style.transform = 'scale('+num+')';
                    document.querySelector('.jsmind').style.transform = 'scale('+num+')';
                    const left = document.querySelector('.theme-primary').getBoundingClientRect().left -120
                    document.querySelector('.theme-primary').style.transform+= 'translateX(-'+left+'px) ';
                    document.querySelector('.jsmind').style.transform+= 'translateX(-'+left+'px) ';
                }
            },
            expandAll() {
                this.jm.expand_all();
            },
            unExpandAll() {
                this.jm.collapse_all();
            },
            downloadImg(){
                this.jm.screenshot.shootDownload()
            },
            // 新增节点
            addNode() {
                var selectedNode = this.jm.get_selected_node() // as parent of new node
                console.log('selected_node', selectedNode)
                if (!selectedNode) { alert('请先选择一个节点'); return }

                var topic = 'new Node'
                this.jm.add_node(selectedNode, 543254354, topic)
                this.dialogVisible = false
            },
            // 删除节点
            onRemoveNode() {
                var selectedId = this.get_selected_nodeid()
                console.log(selectedId)
                if (!selectedId) { alert('请先选择一个节点'); return }
                this.jm.remove_node(selectedId)
            },
            // 获取选中标签的 ID
            get_selected_nodeid() {
                var selectedNode = this.jm.get_selected_node()
                if (selectedNode) {
                    return selectedNode.id.substring(selectedNode.id.lastIndexOf(",") + 1)
                } else {
                    return null
                }
            },
            handleUpload(file) {
                const loading = this.$loading({
                    lock: true,
                    text: '正在导入...',
                    spinner: "el-icon-loading"
                });
                importBomList(file.raw).then(res =>{
                    loading.close();
                    if (res.data.code === 200) {
                        this.$message({
                            type: "success",
                            message: "导入成功!"
                        });
                        this.onLoad(this.page);
                    } else {
                        this.$message({
                            type: "error",
                            message: "导入失败!"
                        });
                    }
                })

            },
        }
    };

</script>

<style>
    @keyframes blink {
        0% {
            opacity: 1;
        }

        50% {
            opacity: 0;
        }

        100% {
            opacity: 1;
        }
    }

    .error {
        animation: blink 3s linear infinite;
        background: red;
    }
</style>
